package xmu.crms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xmu.crms.dto.*;
import xmu.crms.entity.*;
import xmu.crms.exception.*;
import xmu.crms.service.*;
import xmu.crms.util.JwtUtil;
import xmu.crms.vo.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author status200
 * @date 2017/11/30
 */
@RestController
public class GroupController {

    @Autowired
    private SeminarGroupService seminarGroupService;
    @Autowired
    private UserService userService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private SeminarService seminarService;
    /**
     * 获取小组的信息。
     * 小组选择的话题和小组的得分可以通过 GET /group/{groupId}?embedTopics=true&embedGrade=true获取.
     *
     * @param groupId
     * @param embedTopics
     * @param embedGrade
     * @return
     */
    @GetMapping("/group/{groupId}")
    public ResponseEntity<GroupVO> getGroup(@PathVariable("groupId") BigInteger groupId,
                                            @RequestParam(value = "embedTopics", required = false) Boolean embedTopics,
                                            @RequestParam(value = "embedGrade", required = false) Boolean embedGrade) throws GroupNotFoundException, UserNotFoundException {
        GroupVO vo = new GroupVO();
        SeminarGroup seminarGroup=new SeminarGroup();
        seminarGroup=seminarGroupService.getSeminarGroupByGroupId(groupId);

        vo.setId(seminarGroup.getId());
        //TODO
        BigInteger leaderId = seminarGroupService.getSeminarGroupLeaderByGroupId(groupId);

        // 没有设置组长时
        if(leaderId != null) {
            StudentVO leader = new StudentVO();
            leader.setId(leaderId);
            User leader1 = userService.getUserByUserId(leaderId);
            leader.setName(leader1.getName());
            vo.setName(leader1.getName() + "的小组");
            vo.setLeader(leader);
        }

        List<StudentVO> members = new ArrayList<>();
        List<User> userList = seminarGroupService.listSeminarGroupMemberByGroupId(groupId);
        for(User temp : userList){
            StudentVO studentVO = new StudentVO();
            studentVO.setId(temp.getId());
            studentVO.setName(temp.getName());
            members.add(studentVO);
        }
        vo.setMembers(members);

        if (embedTopics != null && embedTopics) {
            List<TopicVO> topics = new ArrayList<>();
            List<SeminarGroupTopic> list = topicService.listSeminarGroupTopicByGroupId(groupId);
            for(SeminarGroupTopic temp : list){
                TopicVO topicVO = new TopicVO();
                topicVO.setId(temp.getTopic().getId());
                topics.add(topicVO);
            }
            vo.setTopics(topics);
        }
        //这里小程序不管报告
        vo.setReport("");

        //小程序这里也不要分数
        if (embedGrade != null && embedGrade) {
            SeminarGradeVO grade = new SeminarGradeVO();
            vo.setGrade(grade);
        }

        return new ResponseEntity<>(vo, HttpStatus.OK);
    }
    //TODO 怀疑要删

    @PutMapping("/group/{groupId}")
    public ResponseEntity updateGroup(@PathVariable("groupId") BigInteger groupId,
                                      @RequestBody GroupDTO dto) {

        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    /**
     * 小程序这里还是不要分数，所以不改
     *
     * @param groupId
     * @return
     */
    @GetMapping("/group/{groupId}/grade")
    public ResponseEntity<SeminarGradeVO> getGroupGrade(@PathVariable("groupId") BigInteger groupId) {

        SeminarGradeVO gradeVO = new SeminarGradeVO();
        List<PresentationGradeVO> presentationGradeVOS = new ArrayList<>();

        PresentationGradeVO presentationGradeVO = new PresentationGradeVO();
        presentationGradeVO.setTopicId(new BigInteger("257"));
        presentationGradeVO.setGrade(new BigInteger("4"));
        presentationGradeVOS.add(presentationGradeVO);

        presentationGradeVO = new PresentationGradeVO();
        presentationGradeVO.setTopicId(new BigInteger("258"));
        presentationGradeVO.setGrade(new BigInteger("5"));
        presentationGradeVOS.add(presentationGradeVO);

        gradeVO.setPresentationGrade(presentationGradeVOS);
        gradeVO.setReportGrade(3);
        gradeVO.setGrade(4);

        return new ResponseEntity<>(gradeVO, HttpStatus.OK);
    }


    @PostMapping("/group/{groupId}/topic")
    public ResponseEntity<UrlVO> chooseTopic(@PathVariable("groupId") BigInteger groupId,
                                             @RequestBody TopicDTO topicDTO) throws GroupNotFoundException, TopicNotFoundException {

        // 获取该topic
        Topic topic = topicService.getTopicByTopicId(topicDTO.getId());

        // 已经被选择的topic的数量
        int topicHasChosen = seminarGroupService.listGroupByTopicId(topicDTO.getId()).size();

        // 选题数量已经满，返回409状态码
        if(topic.getGroupNumberLimit() - topicHasChosen <= 0) {
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }

        seminarGroupService.insertTopicByGroupId(groupId,topicDTO.getId());
        String temp = "/group"+groupId.toString()+"/topic"+topicDTO.getId().toString();
        return new ResponseEntity<>(new UrlVO(temp), HttpStatus.CREATED);
    }

    /**
     * 提交对其他小组的打分
     *
     * @param groupId
     * @param studentId
     * @param dto
     * @return
     */
    @PutMapping("/group/{groupId}/grade/presentation/{studentId}")
    public ResponseEntity grade(@PathVariable("groupId") BigInteger groupId,
                @PathVariable("studentId") BigInteger studentId,
                @RequestBody GroupGradeDTO dto) {
            for(GradeVO temp : dto.getPresentationGrade()){
                gradeService.insertGroupGradeByUserId(studentId,temp.getId(),temp.getGrade());
            }
        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping("/group/{groupId}/assign")
    public ResponseEntity assignLeader(@PathVariable("groupId") BigInteger groupId,
                                       @RequestHeader("Authorization") String authString) throws UserNotFoundException, InfoIllegalException, InvalidOperationException, GroupNotFoundException {
        BigInteger userId = JwtUtil.getIdFromAuthString(authString);
        seminarGroupService.assignLeaderById(groupId,userId);
        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping("/group/{groupId}/resign")
    public ResponseEntity resignLeader(@PathVariable("groupId") BigInteger groupId,
                                       @RequestHeader("Authorization") String authString) throws GroupNotFoundException, UserNotFoundException, InvalidOperationException {
        BigInteger userId = JwtUtil.getIdFromAuthString(authString);
        seminarGroupService.resignLeaderById(groupId,userId);
        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping("/group/{groupId}/add")
    public ResponseEntity addMember(@PathVariable("groupId") BigInteger groupId,@RequestBody UserInfoDTO dto,
                                    @RequestHeader("Authorization") String authString) throws GroupNotFoundException, UserNotFoundException, InvalidOperationException {
        BigInteger userId = dto.getId();
        seminarGroupService.insertSeminarGroupMemberById(userId,groupId);


        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping("/group/{groupId}/remove")
    public ResponseEntity removeMember(@PathVariable("groupId") BigInteger groupId,@RequestBody UserInfoDTO dto,
                                       @RequestHeader("Authorization") String authString) {
        BigInteger userId = dto.getId();
        seminarGroupService.deleteSeminarGroupMemberById(groupId,userId);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}
